#!/usr/bin/env python2.6
"""
Remove books from book collection which are not presented in downloaded database
"""

from pysqlite2 import dbapi2 as sqlite
import glob
import os.path
import os

# change these two variables
## directory with lib.rus.ec archives (i.e. with the files like 109377-110395.zip)
librusec_archives_path = "/home/cancel/lib.rus.ec/archives"
## directory with the local collection of books
collection_path = "/home/cancel/lib.rus.ec/collection"

db = sqlite.connect("database.db")
cursor = db.cursor()

def make_book_path(book_id):
    """
    Make book path for given book_id, book path is something like (3, 9) for the book_id 65493
    """
    s1 = book_id % 10
    s2 = (book_id / 10) % 10
    
    return (s1, s2)

def check_book_presence(book_id):
    query = "SELECT COUNT(*) FROM libbook WHERE BookId=?"
    cursor.execute(query, [book_id])
    row = cursor.fetchone()
    if row[0] != 0:
        return True
    else:
        return False

books_to_delete = []

# find all .fb2.zip files from the collection
for x in range(10):
    for y in range(10):
        files = glob.glob(os.path.join(collection_path, str(x), str(y), "*.fb2.zip"))
        for f in files:
            fb = os.path.basename(f)
            book_id = fb[:fb.find(".")]
            if not check_book_presence(book_id):
                books_to_delete.append(f)

for f in books_to_delete:
    print "deleting %s" % f
    os.unlink(f)
